<template>
  <div class="cart">
    <div class="car-top">
      <van-nav-bar
        title="购物车"
        left-text="返回"
        left-arrow
        fixed
        @click-left="onClickLeft"
      />
    </div>
    <div class="car-main">
      <van-swipe-cell v-for="item in cartinfo" :key="item.product.id">
        <van-card
          :num="item.amount"
          :price="item.product.price"
          :desc="item.product.desc"
          :title="item.product.name"
          class="goods-card"
          :thumb="item.product.coverImage | diaImg"
        >
          <!-- <van-stepper v-model="item.amount" /> -->
          <template #num
            ><van-stepper
              v-model="item.amount"
              min="1"
              @plus="addcar(item.amount, item.product.id, (add = 1))"
              @minus="addcar(item.amount, item.product.id, (miu = -1))"
              @blur="
                addcar(
                  item.amount,
                  item.product.id,
                  (blur = item.amount),
                  (sta = 'blur')
                )
              "
          /></template>
          <template #tag>
            <van-checkbox
              style="background-color: #ff149312"
              v-model="item.checked"
              @change="calPrice"
            ></van-checkbox>
          </template>
        </van-card>
        <template #right>
          <van-button
            square
            text="删除"
            type="danger"
            class="delete-button"
            @click="delCar(item.id)"
          />
        </template>
      </van-swipe-cell>
    <div class="car-foot">
      <van-submit-bar
        :price="price | priDia"
        button-text="提交订单"
        @submit="onSubmit"
      >
        <van-checkbox v-model="checked">全选</van-checkbox>
      </van-submit-bar>
    </div>
  </div>
  </div>
</template>

<script>
import { Notify } from "vant";
import { Toast } from "vant";
import { addcarAPI, cartAPI, delCarAPI } from "../services/carts";
export default {
  data() {
    return {
      cartinfo: [],
      // checked:false,
      price: 0,
    };
  },
  created() {
    this.loadData();
    console.log(JSON.stringify(this.$route.query));
  },
  computed: {
    checked: {
      set(val) {
        console.log(val);
        this.cartinfo.forEach((item) => (item.checked = val));
        //this.price
        this.loadPrice();
      },
      get() {
        return this.cartinfo.every((item) => item.checked);
      },
    },
  },
  methods: {
    async loadData() {
      const res = await cartAPI();
      this.cartinfo = res.data.map((item) => {
         return { ...item, checked: false };
      });
      console.log(JSON.parse(JSON.stringify(this.cartinfo)));
    },
    onClickLeft() {
      this.$router.go(-1);
    },
    async addcar(num, id, step, sta) {
      if (typeof num != "number") {
        console.log("good");
      } else {
        if (sta) {
          const res = await cartAPI();
          // 通过调用接口来查找之前购物车中的数量
          const count = res.data.find((item) => item.product.id == id).amount;
          console.log(step);
          // 将输入框中改变的数量和原来的购物车数量进行相减得出最新的购物车数量
          console.log(step - count);
          addcarAPI({
            product: id,
            amount: step - count,
          }).then((res) => {
            if (res.code == 1) {
              this.loadPrice();
              Notify({
                message: res.msg,
                type: "success",
              });
            } else {
              Notify({
                message: "未知错误",
                type: "error",
              });
            }
          });
        } else {
          addcarAPI({
            product: id,
            amount: step,
          }).then((res) => {
            this.loadPrice();
            if (res.code == 1) {
              Notify({
                message: res.msg,
                type: "success",
              });
            } else {
              Notify({
                message: "未知错误",
                type: "error",
              });
            }
          });
        }
      }
    },
    // 删除购物车数据
    delCar(id) {
      delCarAPI(id).then((res) => {
        if (res.code == 1) {
          Notify({
            message: res.msg,
            type: "success",
          });
          this.loadData();
          this.$store.dispatch("cartsCount/getcars");
        }
      });
    },
    backhome() {
      this.$router.push({
        name: "Home",
      });
    },
    // 单击每个单选框计算价格
    calPrice() {
      this.loadPrice();
    },
    // 公共计算价格的方法
    loadPrice() {
      this.price = this.cartinfo
        .map((item) => {
          return {
            amount: item.amount,
            price: item.product.price,
            checked: item.checked,
          };
        })
        .filter((item) => item.checked)
        .reduce((pre, cur) => pre + cur.amount * cur.price, 0);
    },
    onSubmit() {
      // 选取勾选中的商品
      let selCarts = this.cartinfo.filter((item) => item.checked);
      //  如果没有勾选那么就会弹出提示
      if (selCarts.length == 0) {
        Toast.fail("请选择一项商品亲");
      } else {
        // 将商品信息派发出去
        // this.$store.commit("address/saveCart",selCarts);
        localStorage.setItem("CartInfo",JSON.stringify(selCarts));
        this.$router.push({
           name: "conAddress",
        });
           console.log(JSON.stringify(selCarts));
      }
    },
    onClickEditAddress() {},
  },
};
</script>

<style scoped>
.car {
  display: flex;
  flex-direction: column;
}
.car-top,
.car-foot {
  height: 10vh;
  width: 100vw;
}
.car-main {
  flex: 1;
  overflow: auto;
}
.goods-card {
  margin: 0;
}
.delete-button {
  height: 100%;
}
</style>
